<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

// OneThink常量定义

const ONETHINK_VERSION = '1.1.141212';
const ONETHINK_ADDON_PATH = './Addons/';

/**
 * 系统公共库文件
 * 主要定义系统公共函数库
 */

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function is_login()
{
	$user = session('user_auth');
	if (empty($user)) {
		return 0;
	} else {
		return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
	}
}

/**
 * 检测当前用户是否为管理员
 * @return boolean true-管理员，false-非管理员
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function is_administrator($uid = null)
{
	$uid = is_null($uid) ? is_login() : $uid;

	return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}

/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param        string        $str         要分割的字符串
 * @param        string        $glue        分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ',')
{
	return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param        array         $arr         要连接的数组
 * @param        string        $glue        分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ',')
{
	return implode($glue, $arr);
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param        string        $str            需要转换的字符串
 * @param        string        $start          开始位置
 * @param        string        $length         截取长度
 * @param        string        $charset        编码格式
 * @param        string        $suffix         截断显示字符
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
	if (function_exists("mb_substr"))
		$slice = mb_substr($str, $start, $length, $charset);
	else if (function_exists('iconv_substr')) {
		$slice = iconv_substr($str, $start, $length, $charset);
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("", array_slice($match[0], $start, $length));
	}

	return $suffix ? $slice . '...' : $slice;
}

/**
 * 系统加密方法
 * @param        string        $data          要加密的字符串
 * @param        string        $key           加密密钥
 * @param        int           $expire        过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_encrypt($data, $key = '', $expire = 0)
{
	$key = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
	$data = base64_encode($data);
	$x = 0;
	$len = strlen($data);
	$l = strlen($key);
	$char = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}

	$str = sprintf('%010d', $expire ? $expire + time() : 0);

	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
	}

	return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
}

/**
 * 系统解密方法
 * @param        string        $data        要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param        string        $key         加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_decrypt($data, $key = '')
{
	$key = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
	$data = str_replace(array('-', '_'), array('+', '/'), $data);
	$mod4 = strlen($data) % 4;
	if ($mod4) {
		$data .= substr('====', $mod4);
	}
	$data = base64_decode($data);
	$expire = substr($data, 0, 10);
	$data = substr($data, 10);

	if ($expire > 0 && $expire < time()) {
		return '';
	}
	$x = 0;
	$len = strlen($data);
	$l = strlen($key);
	$char = $str = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}

	for ($i = 0; $i < $len; $i++) {
		if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		} else {
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}

	return base64_decode($str);
}

/**
 * 数据签名认证
 * @param        array        $data        被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data)
{
	//数据类型检测
	if (!is_array($data)) {
		$data = (array)$data;
	}
	ksort($data); //排序
	$code = http_build_query($data); //url编码并生成query字符串
	$sign = sha1($code); //生成签名

	return $sign;
}

/**
 * 对查询结果集进行排序
 * @access public
 * @param        array         $list          查询结果
 * @param        string        $field         排序的字段名
 * @param        array         $sortby        排序类型
 *                                            asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
	if (is_array($list)) {
		$refer = $resultSet = array();
		foreach ($list as $i => $data)
			$refer[$i] = &$data[$field];
		switch ($sortby) {
			case 'asc': // 正向排序
				asort($refer);
				break;
			case 'desc':// 逆向排序
				arsort($refer);
				break;
			case 'nat': // 自然排序
				natcasesort($refer);
				break;
		}
		foreach ($refer as $key => $val)
			$resultSet[] = &$list[$key];

		return $resultSet;
	}

	return false;
}

/**
 * 把返回的数据集转换成Tree
 * @param        array         $list         要转换的数据集
 * @param        string        $pid          parent标记字段
 * @param        string        $level        level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
	// 创建Tree
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] =& $list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId = $data[$pid];
			if ($root == $parentId) {
				$tree[] =& $list[$key];
			} else {
				if (isset($refer[$parentId])) {
					$parent =& $refer[$parentId];
					$parent[$child][] =& $list[$key];
				}
			}
		}
	}

	return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param        array         $tree         原来的树
 * @param        string        $child        孩子节点的键
 * @param        string        $order        排序显示的键，一般是主键 升序排列
 * @param        array         $list         过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array())
{
	if (is_array($tree)) {
		foreach ($tree as $key => $value) {
			$reffer = $value;
			if (isset($reffer[$child])) {
				unset($reffer[$child]);
				tree_to_list($value[$child], $child, $order, $list);
			}
			$list[] = $reffer;
		}
		$list = list_sort_by($list, $order, $sortby = 'asc');
	}

	return $list;
}

/**
 * 格式化字节大小
 * @param        number        $size             字节数
 * @param        string        $delimiter        数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '')
{
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;

	return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 设置跳转页面URL
 * 使用函数再次封装，方便以后选择不同的存储方式（目前使用cookie存储）
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function set_redirect_url($url)
{
	cookie('redirect_url', $url);
}

/**
 * 获取跳转页面URL
 * @return string 跳转页URL
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_redirect_url()
{
	$url = cookie('redirect_url');

	return empty($url) ? __APP__ : $url;
}

/**
 * 处理插件钩子
 * @param        string        $hook          钩子名称
 * @param        mixed         $params        传入参数
 * @return void
 */
function hook($hook, $params = array())
{
	\Think\Hook::listen($hook, $params);
}

/**
 * 获取插件类的类名
 * @param        strng        $name        插件名
 */
function get_addon_class($name)
{
	$class = "Addons\\{$name}\\{$name}Addon";

	return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param        string        $name        插件名
 */
function get_addon_config($name)
{
	$class = get_addon_class($name);
	if (class_exists($class)) {
		$addon = new $class();

		return $addon->getConfig();
	} else {
		return array();
	}
}

/**
 * 插件显示内容里生成访问插件的url
 * @param        string        $url          url
 * @param        array         $param        参数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function addons_url($url, $param = array())
{
	$url = parse_url($url);
	$case = C('URL_CASE_INSENSITIVE');
	$addons = $case ? parse_name($url['scheme']) : $url['scheme'];
	$controller = $case ? parse_name($url['host']) : $url['host'];
	$action = trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if (isset($url['query'])) {
		parse_str($url['query'], $query);
		$param = array_merge($query, $param);
	}

	/* 基础参数 */
	$params = array(
		'_addons' => $addons,
		'_controller' => $controller,
		'_action' => $action,
	);
	$params = array_merge($params, $param); //添加额外参数

	return U('Addons/execute', $params);
}

/**
 * 时间戳格式化
 * @param        int        $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = null, $format = 'Y-m-d H:i')
{
	$time = $time === null ? NOW_TIME : intval($time);

	return date($format, $time);
}

/**
 * 根据用户ID获取用户名
 * @param        integer        $uid        用户ID
 * @return string       用户名
 */
function get_username($uid = 0)
{
	static $list;
	if (!($uid && is_numeric($uid))) { //获取当前登录用户名
		return session('user_auth.username');
	}

	/* 获取缓存数据 */
	if (empty($list)) {
		$list = S('sys_active_user_list');
	}

	/* 查找用户信息 */
	$key = "u{$uid}";
	if (isset($list[$key])) { //已缓存，直接使用
		$name = $list[$key];
	} else { //调用接口获取用户信息
		$User = new User\Api\UserApi();
		$info = $User->info($uid);
		if ($info && isset($info[1])) {
			$name = $list[$key] = $info[1];
			/* 缓存用户 */
			$count = count($list);
			$max = C('USER_MAX_CACHE');
			while ($count-- > $max) {
				array_shift($list);
			}
			S('sys_active_user_list', $list);
		} else {
			$name = '';
		}
	}

	return $name;
}

/**
 * 根据用户ID获取用户昵称
 * @param        integer        $uid        用户ID
 * @return string       用户昵称
 */
function get_nickname($uid = 0)
{
	static $list;
	if (!($uid && is_numeric($uid))) { //获取当前登录用户名
		return session('user_auth.username');
	}

	/* 获取缓存数据 */
	if (empty($list)) {
		$list = S('sys_user_nickname_list');
	}

	/* 查找用户信息 */
	$key = "u{$uid}";
	if (isset($list[$key])) { //已缓存，直接使用
		$name = $list[$key];
	} else { //调用接口获取用户信息
		$info = M('Member')->field('nickname')->find($uid);
		if ($info !== false && $info['nickname']) {
			$nickname = $info['nickname'];
			$name = $list[$key] = $nickname;
			/* 缓存用户 */
			$count = count($list);
			$max = C('USER_MAX_CACHE');
			while ($count-- > $max) {
				array_shift($list);
			}
			S('sys_user_nickname_list', $list);
		} else {
			$name = '';
		}
	}

	return $name;
}

/**
 * 获取分类信息并缓存分类
 * @param        integer        $id           分类ID
 * @param        string         $field        要获取的字段名
 * @return string         分类信息
 */
function get_category($id, $field = null)
{
	static $list;

	/* 非法分类ID */
	if (empty($id) || !is_numeric($id)) {
		return '';
	}

	/* 读取缓存数据 */
	if (empty($list)) {
		$list = S('sys_category_list');
	}

	/* 获取分类名称 */
	if (!isset($list[$id])) {
		$cate = M('Category')->find($id);
		if (!$cate || 1 != $cate['status']) { //不存在分类，或分类被禁用
			return '';
		}
		$list[$id] = $cate;
		S('sys_category_list', $list); //更新缓存
	}

	return is_null($field) ? $list[$id] : $list[$id][$field];
}

/* 根据ID获取分类标识 */
function get_category_name($id)
{
	return get_category($id, 'name');
}

/* 根据ID获取分类名称 */
function get_category_title($id)
{
	return get_category($id, 'title');
}

/**
 * 获取顶级模型信息
 */
function get_top_model($model_id = null)
{
	$map = array('status' => 1, 'extend' => 0);
	if (!is_null($model_id)) {
		$map['id'] = array('neq', $model_id);
	}
	$model = M('Model')->where($map)->field(true)->select();
	foreach ($model as $value) {
		$list[$value['id']] = $value;
	}

	return $list;
}

/**
 * 获取文档模型信息
 * @param        integer        $id           模型ID
 * @param        string         $field        模型字段
 * @return array
 */
function get_document_model($id = null, $field = null)
{
	static $list;

	/* 非法分类ID */
	if (!(is_numeric($id) || is_null($id))) {
		return '';
	}

	/* 读取缓存数据 */
	if (empty($list)) {
		$list = S('DOCUMENT_MODEL_LIST');
	}

	/* 获取模型名称 */
	if (empty($list)) {
		$map = array('status' => 1, 'extend' => 1);
		$model = M('Model')->where($map)->field(true)->select();
		foreach ($model as $value) {
			$list[$value['id']] = $value;
		}
		S('DOCUMENT_MODEL_LIST', $list); //更新缓存
	}

	/* 根据条件返回数据 */
	if (is_null($id)) {
		return $list;
	} else if (is_null($field)) {
		return $list[$id];
	} else {
		return $list[$id][$field];
	}
}

/**
 * 解析UBB数据
 * @param        string        $data        UBB字符串
 * @return string 解析为HTML的数据
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function ubb($data)
{
	//TODO: 待完善，目前返回原始数据
	return $data;
}

/**
 * 记录行为日志，并执行该行为的规则
 * @param        string        $action           行为标识
 * @param        string        $model            触发行为的模型名
 * @param        int           $record_id        触发行为的记录id
 * @param        int           $user_id          执行行为的用户id
 * @return boolean
 * @author huajie <banhuajie@163.com>
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null)
{

	//参数检查
	if (empty($action) || empty($model) || empty($record_id)) {
		return '参数不能为空';
	}
	if (empty($user_id)) {
		$user_id = is_login();
	}

	//查询行为,判断是否执行
	$action_info = M('Action')->getByName($action);
	if ($action_info['status'] != 1) {
		return '该行为被禁用或删除';
	}

	//插入行为日志
	$data['action_id'] = $action_info['id'];
	$data['user_id'] = $user_id;
	$data['action_ip'] = ip2long(get_client_ip());
	$data['model'] = $model;
	$data['record_id'] = $record_id;
	$data['create_time'] = NOW_TIME;

	//解析日志规则,生成日志备注
	if (!empty($action_info['log'])) {
		if (preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)) {
			$log['user'] = $user_id;
			$log['record'] = $record_id;
			$log['model'] = $model;
			$log['time'] = NOW_TIME;
			$log['data'] = array('user' => $user_id, 'model' => $model, 'record' => $record_id, 'time' => NOW_TIME);
			foreach ($match[1] as $value) {
				$param = explode('|', $value);
				if (isset($param[1])) {
					$replace[] = call_user_func($param[1], $log[$param[0]]);
				} else {
					$replace[] = $log[$param[0]];
				}
			}
			$data['remark'] = str_replace($match[0], $replace, $action_info['log']);
		} else {
			$data['remark'] = $action_info['log'];
		}
	} else {
		//未定义日志规则，记录操作url
		$data['remark'] = '操作url：' . $_SERVER['REQUEST_URI'];
	}

	M('ActionLog')->add($data);

	if (!empty($action_info['rule'])) {
		//解析行为
		$rules = parse_action($action, $user_id);

		//执行行为
		$res = execute_action($rules, $action_info['id'], $user_id);
	}
}

/**
 * 解析行为规则
 * 规则定义  table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
 * 规则字段解释：table->要操作的数据表，不需要加表前缀；
 *              field->要操作的字段；
 *              condition->操作的条件，目前支持字符串，默认变量{$self}为执行行为的用户
 *              rule->对字段进行的具体操作，目前支持四则混合运算，如：1+score*2/2-3
 *              cycle->执行周期，单位（小时），表示$cycle小时内最多执行$max次
 *              max->单个周期内的最大执行次数（$cycle和$max必须同时定义，否则无效）
 * 单个行为后可加 ； 连接其他规则
 * @param        string        $action        行为id或者name
 * @param        int           $self          替换规则里的变量为执行用户的id
 * @return boolean|array: false解析出错 ， 成功返回规则数组
 * @author huajie <banhuajie@163.com>
 */
function parse_action($action = null, $self)
{
	if (empty($action)) {
		return false;
	}

	//参数支持id或者name
	if (is_numeric($action)) {
		$map = array('id' => $action);
	} else {
		$map = array('name' => $action);
	}

	//查询行为信息
	$info = M('Action')->where($map)->find();
	if (!$info || $info['status'] != 1) {
		return false;
	}

	//解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
	$rules = $info['rule'];
	$rules = str_replace('{$self}', $self, $rules);
	$rules = explode(';', $rules);
	$return = array();
	foreach ($rules as $key => &$rule) {
		$rule = explode('|', $rule);
		foreach ($rule as $k => $fields) {
			$field = empty($fields) ? array() : explode(':', $fields);
			if (!empty($field)) {
				$return[$key][$field[0]] = $field[1];
			}
		}
		//cycle(检查周期)和max(周期内最大执行次数)必须同时存在，否则去掉这两个条件
		if (!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])) {
			unset($return[$key]['cycle'], $return[$key]['max']);
		}
	}

	return $return;
}

/**
 * 执行行为
 * @param        array        $rules            解析后的规则数组
 * @param        int          $action_id        行为id
 * @param        array        $user_id          执行的用户id
 * @return boolean false 失败 ， true 成功
 * @author huajie <banhuajie@163.com>
 */
function execute_action($rules = false, $action_id = null, $user_id = null)
{
	if (!$rules || empty($action_id) || empty($user_id)) {
		return false;
	}

	$return = true;
	foreach ($rules as $rule) {

		//检查执行周期
		$map = array('action_id' => $action_id, 'user_id' => $user_id);
		$map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600);
		$exec_count = M('ActionLog')->where($map)->count();
		if ($exec_count > $rule['max']) {
			continue;
		}

		//执行数据库操作
		$Model = M(ucfirst($rule['table']));
		$field = $rule['field'];
		$res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule']));

		if (!$res) {
			$return = false;
		}
	}

	return $return;
}

//基于数组创建目录和文件
function create_dir_or_files($files)
{
	foreach ($files as $key => $value) {
		if (substr($value, -1) == '/') {
			mkdir($value);
		} else {
			@file_put_contents($value, '');
		}
	}
}

if (!function_exists('array_column')) {
	function array_column(array $input, $columnKey, $indexKey = null)
	{
		$result = array();
		if (null === $indexKey) {
			if (null === $columnKey) {
				$result = array_values($input);
			} else {
				foreach ($input as $row) {
					$result[] = $row[$columnKey];
				}
			}
		} else {
			if (null === $columnKey) {
				foreach ($input as $row) {
					$result[$row[$indexKey]] = $row;
				}
			} else {
				foreach ($input as $row) {
					$result[$row[$indexKey]] = $row[$columnKey];
				}
			}
		}

		return $result;
	}
}

/**
 * 获取表名（不含表前缀）
 * @param        string        $model_id
 * @return string 表名
 * @author huajie <banhuajie@163.com>
 */
function get_table_name($model_id = null)
{
	if (empty($model_id)) {
		return false;
	}
	$Model = M('Model');
	$name = '';
	$info = $Model->getById($model_id);
	if ($info['extend'] != 0) {
		$name = $Model->getFieldById($info['extend'], 'name') . '_';
	}
	$name .= $info['name'];

	return $name;
}

/**
 * 获取属性信息并缓存
 * @param        integer        $id           属性ID
 * @param        string         $field        要获取的字段名
 * @return string         属性信息
 */
function get_model_attribute($model_id, $group = true, $fields = true)
{
	static $list;

	/* 非法ID */
	if (empty($model_id) || !is_numeric($model_id)) {
		return '';
	}

	/* 获取属性 */
	if (!isset($list[$model_id])) {
		$map = array('model_id' => $model_id);
		$extend = M('Model')->getFieldById($model_id, 'extend');

		if ($extend) {
			$map = array('model_id' => array("in", array($model_id, $extend)));
		}
		$info = M('Attribute')->where($map)->field($fields)->select();
		$list[$model_id] = $info;
	}

	$attr = array();
	if ($group) {
		foreach ($list[$model_id] as $value) {
			$attr[$value['id']] = $value;
		}
		$model = M("Model")->field("field_sort,attribute_list,attribute_alias")->find($model_id);
		$attribute = explode(",", $model['attribute_list']);
		if (empty($model['field_sort'])) { //未排序
			$group = array(1 => array_merge($attr));
		} else {
			$group = json_decode($model['field_sort'], true);

			$keys = array_keys($group);
			foreach ($group as &$value) {
				foreach ($value as $key => $val) {
					$value[$key] = $attr[$val];
					unset($attr[$val]);
				}
			}

			if (!empty($attr)) {
				foreach ($attr as $key => $val) {
					if (!in_array($val['id'], $attribute)) {
						unset($attr[$key]);
					}
				}
				$group[$keys[0]] = array_merge($group[$keys[0]], $attr);
			}
		}
		if (!empty($model['attribute_alias'])) {
			$alias = preg_split('/[;\r\n]+/s', $model['attribute_alias']);
			$fields = array();
			foreach ($alias as &$value) {
				$val = explode(':', $value);
				$fields[$val[0]] = $val[1];
			}
			foreach ($group as &$value) {
				foreach ($value as $key => $val) {
					if (!empty($fields[$val['name']])) {
						$value[$key]['title'] = $fields[$val['name']];
					}
				}
			}
		}
		$attr = $group;
	} else {
		foreach ($list[$model_id] as $value) {
			$attr[$value['name']] = $value;
		}
	}

	return $attr;
}

/**
 * 调用系统的API接口方法（静态方法）
 * api('User/getName','id=5'); 调用公共模块的User接口的getName方法
 * api('Admin/User/getName','id=5');  调用Admin模块的User接口
 * @param        string              $name        格式 [模块名]/接口名/方法名
 * @param        array|string        $vars        参数
 */
function api($name, $vars = array())
{
	$array = explode('/', $name);
	$method = array_pop($array);
	$classname = array_pop($array);
	$module = $array ? array_pop($array) : 'Common';
	$callback = $module . '\\Api\\' . $classname . 'Api::' . $method;
	if (is_string($vars)) {
		parse_str($vars, $vars);
	}

	return call_user_func_array($callback, $vars);
}

/**
 * 根据条件字段获取指定表的数据
 * @param        mixed         $value            条件，可用常量或者数组
 * @param        string        $condition        条件字段
 * @param        string        $field            需要返回的字段，不传则返回整个数据
 * @param        string        $table            需要查询的表
 * @author huajie <banhuajie@163.com>
 */
function get_table_field($value = null, $condition = 'id', $field = null, $table = null)
{
	if (empty($value) || empty($table)) {
		return false;
	}

	//拼接参数
	$map[$condition] = $value;
	$info = M(ucfirst($table))->where($map);
	if (empty($field)) {
		$info = $info->field(true)->find();
	} else {
		$info = $info->getField($field);
	}

	return $info;
}

/**
 * 获取链接信息
 * @param        int           $link_id
 * @param        string        $field
 * @return 完整的链接信息或者某一字段
 * @author huajie <banhuajie@163.com>
 */
function get_link($link_id = null, $field = 'url')
{
	$link = '';
	if (empty($link_id)) {
		return $link;
	}
	$link = M('Url')->getById($link_id);
	if (empty($field)) {
		return $link;
	} else {
		return $link[$field];
	}
}

/**
 * 获取文档封面图片
 * @param        int           $cover_id
 * @param        string        $field
 * @return 完整的数据  或者  指定的$field字段值
 * @author huajie <banhuajie@163.com>
 */
function get_cover($cover_id, $field = null)
{
	if (empty($cover_id)) {
		return false;
	}
	$picture = M('Picture')->where(array('status' => 1))->getById($cover_id);
	if ($field == 'path') {
		if (!empty($picture['url'])) {
			$picture['path'] = $picture['url'];
		} else {
			$picture['path'] = __ROOT__ . $picture['path'];
		}
	}

	return empty($field) ? $picture : $picture[$field];
}

/**
 * 检查$pos(推荐位的值)是否包含指定推荐位$contain
 * @param        number        $pos            推荐位的值
 * @param        number        $contain        指定推荐位
 * @return boolean true 包含 ， false 不包含
 * @author huajie <banhuajie@163.com>
 */
function check_document_position($pos = 0, $contain = 0)
{
	if (empty($pos) || empty($contain)) {
		return false;
	}

	//将两个参数进行按位与运算，不为0则表示$contain属于$pos
	$res = $pos & $contain;
	if ($res !== 0) {
		return true;
	} else {
		return false;
	}
}

/**
 * 获取数据的所有子孙数据的id值
 * @author 朱亚杰 <xcoolcc@gmail.com>
 */

function get_stemma($pids, Model &$model, $field = 'id')
{
	$collection = array();

	//非空判断
	if (empty($pids)) {
		return $collection;
	}

	if (is_array($pids)) {
		$pids = trim(implode(',', $pids), ',');
	}
	$result = $model->field($field)->where(array('pid' => array('IN', (string)$pids)))->select();
	$child_ids = array_column((array)$result, 'id');

	while (!empty($child_ids)) {
		$collection = array_merge($collection, $result);
		$result = $model->field($field)->where(array('pid' => array('IN', $child_ids)))->select();
		$child_ids = array_column((array)$result, 'id');
	}

	return $collection;
}

/**
 * 验证分类是否允许发布内容
 * @param        integer        $id        分类ID
 * @return boolean     true-允许发布内容，false-不允许发布内容
 */
function check_category($id)
{
	if (is_array($id)) {
		$id['type'] = !empty($id['type']) ? $id['type'] : 2;
		$type = get_category($id['category_id'], 'type');
		$type = explode(",", $type);

		return in_array($id['type'], $type);
	} else {
		$publish = get_category($id, 'allow_publish');

		return $publish ? true : false;
	}
}

/**
 * 检测分类是否绑定了指定模型
 * @param        array        $info        模型ID和分类ID数组
 * @return boolean     true-绑定了模型，false-未绑定模型
 */
function check_category_model($info)
{
	$cate = get_category($info['category_id']);
	$array = explode(',', $info['pid'] ? $cate['model_sub'] : $cate['model']);

	return in_array($info['model_id'], $array);
}

/***********以下封装方法是自己写的***********/
/**
 * 按综合方式输出通信数据
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $data          数据
 * @return string
 */
function api_return($result, $msg = '', $data = false)
{
	if (!is_numeric($result)) {
		return '';
	}

	return api_json($result, $msg, $data);
}

/**
 * 按json方式输出通信数据
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $data          数据
 * @return string
 */
function api_json($result, $msg = '', $data = false)
{

	if (!is_numeric($result)) {
		return '';
	}

	if ($data > 0 || $data === []) {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'data' => $data ? $data : []
		);
	} else {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'data' => $data ? $data : ''
		);
	}

	echo json_encode($message);
	exit;
}

/**
 * 短信发送
 * @param        string        $mobile        手机号
 * @param        int           $type          类型
 * @param        array         $array         携带参数
 * @return json
 * */
function send_notice_sms($mobile, $array = [])
{
	//获取手机号
	if (empty($mobile)) {
//        return api_return(2,'手机号不能为空');
	} else {
		$content = '【犀牛搬家】有用户提交了新的订单：' . $array['order_sn'] . '，用户手机号为：' . $array['mobile'] . '，请及时前往后台处理。';
		$statusStr = array(
			"0" => 1,
			"-1" => "参数不全",
			"-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
			"30" => "密码错误2",
			"40" => "账号不存在",
			"41" => "余额不足",
			"42" => "帐户已过期",
			"43" => "IP地址限制",
			"50" => "内容含有敏感词",
			"51" => "手机号码不正确"
		);
		$smsapi = "http://api.smsbao.com/";
		$user = C('WEB_SMS_ACC'); //短信平台帐号
		$pass = md5(C('WEB_SMS_PWD')); //短信平台密码
		$phone = $mobile;//要发送短信的手机号码
		$sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
		$res = file_get_contents($sendurl);
//        file_put_contents(RUNTIME_PATH.'sms_result.txt',$res);
	}
}

/**
 * 获取省id
 * @param        string        $province_name        省名称
 * @return int
 * */
function getProvinceId($province_name)
{
	$province_id = M('province')->where(['name' => $province_name])->getField('province_id');

	return $province_id;
}

/**
 * 获取省名称
 * @param        int        $province_id        省id
 * @return string
 * */
function getProvinceName($province_id)
{
	$name = M('province')->where(array('province_id' => $province_id))->getField('name');

	return $name ? $name : '';
}

/**
 * 获取市id
 * @param        string        $province_name        省名称
 * @param        string        $city_name            市名称
 * @return int
 * */
function getCityId($province_name, $city_name)
{
	$province_id = getProvinceId($province_name);

	$city_name = str_replace(array('市', '省'), '', $city_name);
	$city_id = M('city')->where(array('province_id' => $province_id, 'name' => array('like', $city_name . '%')))->getField('city_id');

	return $city_id;
}

/**
 * 获取市名称
 * @param        int        $city_id        市id
 * @return string
 * */
function getCityName($city_id)
{
	$name = M('city')->where(array('city_id' => $city_id))->getField('name');

	return $name ? $name : '';
}

/**
 * 获取区id
 * @param        string        $province_name        省名称
 * @param        string        $city_name            市名称
 * @param        string        $area_name            市名称
 * @return int
 * */
function getAreaId($province_name, $city_name, $area_name)
{
	$city_id = getCityId($province_name, $city_name);

	$area_name = str_replace(array('市', '区', '县'), '', $area_name);
	$area_id = M('area')->where(array('city_id' => $city_id, 'name' => array('like', $area_name . '%')))->getField('area_id');

	return $area_id;
}

/**
 * 获取区名称
 * @param        int        $area_id        区id
 * @return string
 * */
function getAreaName($area_id)
{
	$name = M('area')->where(array('area_id' => $area_id))->getField('name');

	return $name ? $name : '';
}

/**
 * 用户头像处理
 * @param        int        $avatar_id        用户头像ID 或 用户头像路径
 * @return string
 * */
function doAvatar($avatar_id)
{
	if (strlen($avatar_id) < 10) {
		//此时用户头像为修改之后的头像
		$avatar = getPicture($avatar_id);
	} else {
		$avatar = $avatar_id;
	}

	return $avatar ? $avatar : '';
}

/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param        string        $day1
 * @param        string        $day2
 * @return number
 */
function diffBetweenTwoDays($day1, $day2)
{
	$second1 = strtotime($day1);
	$second2 = strtotime($day2);

	if ($second1 < $second2) {
		$tmp = $second2;
		$second2 = $second1;
		$second1 = $tmp;
	}

	return ($second1 - $second2) / 86400;
}

/**
 * 获取用户的基本信息
 * @param        string        $field        查询字段
 * @param        int           $uid          用户id
 * @return  array
 * */
function getUserInfo($uid, $field = '*')
{
	$userInfo = M('ucenter_member')->field($field)->where(['id' => $uid])->find();
	if ($userInfo) {
		$userInfo['avatar'] = doAvatar($userInfo['avatar']);

		return $userInfo;
	} else {
		return [];
	}
}

/**
 * 请求过程中因为编码原因+号变成了空格
 * 需要用下面的方法转换回来
 */
function define_str_replace($data)
{
	return str_replace(' ', '+', $data);
}

/**
 * 获取文件扩展名
 * @param $filename  varchar  文件路径
 * @return mixed
 */
function getExtension($filename)
{
	$myext = substr($filename, strrpos($filename, '.'));

	return str_replace('.', '', $myext);
}

/**
 * 获取域名前缀
 * */
function getHost()
{
	$res = is_ssl();
	if ($res) {
		return 'https://' . $_SERVER['HTTP_HOST'];
	} else {
		return 'http://' . $_SERVER['HTTP_HOST'];
	}
}

/**
 * 根据图片id获取图片路径
 * */
function getPicture($id)
{
	$path = M('picture')->where(['id' => $id])->getField('path');
	if ($path) {
		return getHost() . $path;
	} else {
		return '';
	}
}

/**
 * 多图处理
 * @param        string        $imgs           图片id集合
 * @param        string        $img_key        自定义图片路径下标
 * @return array
 * */
function doImgs($imgs, $img_key = 'path')
{
	$img_arr = explode(',', $imgs);

	if ($img_arr) {
		$new_img_arr = [];
		foreach ($img_arr as $k => &$v) {
			$new_img_arr[$k]['id'] = $v;
			$new_img_arr[$k][$img_key] = getPicture($v);
		}
	}

	return $new_img_arr ? $new_img_arr : [];
}

/**
 * 单图上传
 * @param        file        $file        图片文件
 * @param        int         $uid         当前登录用户id
 * @param        int         $type        上传图片的类型 1：身份证正面；2：身份证反面；3：营业执照；4：在线课视频提问图片
 * @return       json
 * */
function uploadImg($file, $uid, $type = 0)
{
	if (empty($uid)) return api_return(2, '用户ID不能为空');

	if ($type == 1) {
		$type_file = 'Uploads/Picture/card_z/';
	} else if ($type == 2) {
		$type_file = 'Uploads/Picture/card_f/';
	} else if ($type == 3) {
		$type_file = 'Uploads/Picture/yyzz/';
	} else {
		$type_file = 'Uploads/Picture/';
	}

	$save_picture_path = $type_file . date("Y-m-d");
	if (!is_dir($save_picture_path)) mkdir($save_picture_path, 0777, true);

	if ($file['name'] == '') {
		return api_return(2, '请上传图片');
	} else {
		if (is_uploaded_file($file['tmp_name'])) {
			$str = getExtension($file['name']);
			$avatar_path = $type_file . date("Y-m-d") . "/" . time() . rand(1000, 9999) . $uid . '.' . $str;

			if (copy($file['tmp_name'], $avatar_path)) {
				$cover['path'] = "/" . $avatar_path;
				$cover['status'] = 1;
				$cover['create_time'] = time();
				$result_avatar_id = M('picture')->add($cover);

				if ($result_avatar_id) {
					unlink($file['tmp_name']);
					$data = [
						'id' => $result_avatar_id,
						'img' => getPicture($result_avatar_id)
					];

					return api_return(1, '图片上传成功', $data);
				} else {
					return api_return(2, '图片上传失败');
				}
			} else {
				return api_return(2, '图片上传失败');
			}
		}
	}
}

/**
 * 获取某个表中的某一个表字段值
 * @param   $db         string      表名
 * @param   $where      array       条件
 * @param   $field      string      字段名
 * @return  string
 * */
function getDbFieldValue($db, $where, $field)
{
	$result = M($db)->where($where)->getField($field);

	return $result ? $result : '';
}

/**
 * 处理机构审核状态
 * @param       $status     int     审核状态
 * @return      string
 * */
function doInstitutionStatus($status)
{
	$status_str = '';
	if ($status == 0) {
		$status_str = '待审核';
	} else if ($status == 1) {
		$status_str = '审核成功';
	} else if ($status_str == 2) {
		$status_str = '审核失败';
	}

	return $status_str;
}

/**
 * 处理图片类型
 * @param       $style     int     图片类型
 * @return      string
 * */
function doPictureStyle($style)
{
	$style_str = '';
	if ($style == 0) {
		$style_str = '普通图片';
	} else if ($style == 1) {
		$style_str = '长期图片';
	} else if ($style == 2) {
		$style_str = '定期图片';
	}

	return $style_str;
}

/**
 * 订单状态处理
 * @param       $status     int         订单状态
 * */
function doOrderStatus($status)
{
	$status_str = '';
	switch ($status) {
		case 1:
			$status_str = '待发货';
			break;
		case 2:
			$status_str = '待收货';
			break;
		case 3:
			$status_str = '待评价';
			break;
		case 4:
			$status_str = '已完成';
			break;
		case 5:
			$status_str = '已过期';
			break;
		case 6:
			$status_str = '售后中';
			break;
		case 7:
			$status_str = '退款中';
			break;
		case 8:
			$status_str = '已取消';
			break;
	}

	return $status_str;
}

/**
 * 腾讯云获取userSig签名
 * @param       $userID     string      用户名，自定义
 * @return      string
 * */
function getUserSig($userID)
{
	vendor('getUserSig.autoload');

	$config = api('Config/lists');

	$api = new \Tencent\TLSSigAPIv2($config['YUNSDKAPPID'], $config['YUNSECRET']);
	$userSig = $api->genSig($userID);

	return $userSig;
}

/**
 * 生成一个随机用户id_account（可用于登录H5端）
 * @return        int
 * */
function getRandIdAccount()
{
	$userId = rand(100000, 999999);

	$count = M('ucenter_member')->where(array('id_account' => $userId))->count();
	if ($count == 0) {
		return $userId;
	} else {
		return getRandUserId();
	}
}

/**
 * 获取直播时间列表
 * */
function getListTimeList()
{
	$date_arr = array();

	for ($i = 0; $i < 6; $i++) {
		$desc = date('m.d', strtotime('+' . $i . ' day'));
		$date = date('Y-m-d', strtotime('+' . $i . ' day'));

		if ($i == 0) {
			$desc = '今日';
		} else if ($i == 1) {
			$desc = '明日';
		}
		$date_arr[] = array(
			'desc' => $desc,
			'date' => $date,
			'active' => ''
		);
	}
	$empty_arr = array(
		array(
			'desc' => '全部',
			'date' => 0,
			'active' => 'active'
		)
	);

	return array_merge($empty_arr, $date_arr);
}

/**
 * 获取在线课课程分类名称
 * */
function getVideoCourseType($id)
{
	$type_name = M('video_course_type')->where(array('id' => $id))->getField('name');

	return $type_name ? $type_name : '';
}

/**
 * 获取课程节数
 * @param        int        $vc_id        video_course主键id
 * */
function videoTreeCount($vc_id)
{
	$copy_id = M('video_course')->where(array('id' => $vc_id))->getField('copy_id');

	if ($copy_id) {
		$count = M('video_tree')->where(array('vc_id' => $copy_id, 'type' => 2))->count();
	} else {
		$count = 0;
	}

	return $count ? $count : 0;
}

/**
 * 获取某个课程在第几节
 * @param        int        $vc_id        课程ID
 * @param        int        $vt_id        视频ID
 * @return       int
 * */
function getTreeSection($vc_id, $vt_id)
{
	$pid = M('video_tree')->where(array('id' => $vt_id))->getField('pid');

	$copy_id = M('video_course')->where(array('id' => $vc_id))->getField('copy_id');

	if ($copy_id) {
		$list = M('video_tree')->field('id')->where(array('vc_id' => $copy_id, 'type' => 1))->select();
		if ($list) {
			$section_count = 0;
			for ($i = 0; $i < count($list); $i++) {
				if ($list[$i]['id'] != $pid) {
					$section_count += M('video_tree')->where(array('pid' => $list[$i]['id']))->count();
				} else {
					$tree_list = M('video_tree')->where(array('pid' => $list[$i]['id']))->select();
					for ($j = 0; $j < count($tree_list); $j++) {
						if ($tree_list[$j]['id'] == $vt_id) {
							++$section_count;
							break;
						} else {
							++$section_count;
						}
					}
					break;
				}
			}
		}
	} else {
		$section_count = 0;
	}

	return $section_count;
}

/**
 * 观看时长格式化
 * @param        int        $duration        观看时长
 * */
function durationFormat($duration)
{
	if ($duration > 3600) {
		//小时：分钟：秒
		$hours = floor($duration / 3600);
		$min = floor(($duration - $hours * 3600) / 60);
		$sec = $duration - $hours * 3600 - $min * 60;

		return ($hours >= 10 ? $hours : '0' . $hours) . ':' . ($min >= 10 ? $min : '0' . $min) . ':' . ($sec >= 10 ? $sec : '0' . $sec);
	} else {
		//分钟：秒
		$min = floor($duration / 60);
		$sec = $duration - $min * 60;

		return ($min >= 10 ? $min : '0' . $min) . ':' . ($sec >= 10 ? $sec : '0' . $sec);
	}
}

/**
 * 数值不够补零
 * @param        string        $str
 * @param        int           $len        长度
 * */
function addZero($str, $len = 4)
{
	$str_len = strlen($str);
	if ($str_len >= $len) {
		return $str;
	} else {
		$zero = '';
		for ($i = 0; $i < $len - $str_len; $i++) {
			$zero .= '0';
		}

		return $zero . $str;
	}
}

/**
 * 统计 练习/试卷 平均正确率 && 做过的人数
 * @paran       int     $id     练习/试卷ID
 * @return      array
 * */
function getPracticeTrueRate($id)
{
	//平均正确率
	$all_rate_avg = M('user_test_log')->where(array('practice_id' => $id))->avg('all_rate');
	//做过的人数
	$list = M('user_test_log')->distinct(true)->field('uid')->where(array('practice_id' => $id))->select();

	$data = array(
		'all_rate_avg' => $all_rate_avg,
		'write_count' => count($list)
	);

	return $data;
}

/**
 * 获取 章节/知识点 名称
 * @param        int        $id        章节/知识点ID
 * @return       string
 * */
function getChapterName($id)
{
	$name = M('chapter')->where(array('id' => $id))->getField('name');

	return $name ? $name : '';
}

/**
 * 获取学科名称
 * @param        int        $id        学科ID
 * @return       string
 * */
function getSubjectName($id)
{
	$name = M('subject')->where(array('id' => $id))->getField('name');

	return $name ? $name : '';
}

/**
 * 获取 练习册/试卷 所属模块
 * @param        int        $style
 * @return       string
 * */
function getPracticeStyleDesc($style)
{
	switch ($style) {
		case 1  :
			return '章节练习';
			break;
		case 2  :
			return '巩固考试';
			break;
		case 3  :
			return '真题模考';
			break;
		case 4  :
			return '精品试卷';
			break;
	}
}

/**
 * 解码Unicode字符
 * */
function decodeUnicode($str)
{
	return preg_replace_callback(
		'/\\\\u([0-9a-f]{4})/i',
		create_function(
			'$matches',
			'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
		),
		$str
	);
}

/**
 * 学习时长格式化
 * @param        int        $duration        学习时长
 * */
function studyTimeFormat($duration)
{
	if ($duration > 3600 * 24) {
		//天：小时：分钟
		$day = floor($duration / (3600 * 24));
		$hours = floor(($duration - $day * 3600 * 24) / 3600);
		$min = floor(($duration - $day * 3600 * 24 - $hours * 3600) / 60);

		return $day . '天' . ($hours >= 10 ? $hours : '0' . $hours) . '时' . ($min >= 10 ? $min : '0' . $min) . '分';
	} else if ($duration > 3600) {
		//小时：分钟
		$hours = floor($duration / 3600);
		$min = floor(($duration - $hours * 3600) / 60);

		return ($hours >= 10 ? $hours : '0' . $hours) . '时' . ($min >= 10 ? $min : '0' . $min) . '分';
	} else {
		//分钟：秒
		$min = floor($duration / 60);

		return $min . '分';
	}
}

/**
 * 获取点播课程获取学习到第几节信息
 * @param        int        $vc_id        课程id
 * @return       array
 * */
function getVideoCourseStudyInfo($vc_id)
{
	$info = M('video_study')->field('duration,section,vt_id')->where(array('vc_id' => $vc_id))->order('study_time desc')->find();
	if ($info) {
		return $info;
	} else {
		return array();
	}
}

/**
 * 获取用户点播课程过期时间
 * @param        int        $uid        用户ID
 * @param        int        $id         点播课程ID
 * @return       int
 * */
function getUserVideoCourseExpireTime($uid, $id)
{
	$expire_time = getDbFieldValue('user_video_course', array('uid' => $uid, 'vc_id' => $id), 'expire_time');

	return $expire_time ? $expire_time : 0;
}

/**
 * 获取上级用户ID
 * @param        int        $uid        用户id
 * @return       int
 * */
function getShareUid($uid)
{
	$share_uid = M('ucenter_member')->where(array('id' => $uid))->getField('share_uid');

	return $share_uid ? $share_uid : 0;
}

/**
 * 获取用户当前可使用的优惠券列表
 * @param        int        $uid          用户ID
 * @param        int        $price        金额
 * @param        int        $type         1：面授课，2：点播课，3：直播课，4：书籍
 * @return       array
 * */
function getUserCoupon($uid, $price, $type)
{
	if ($uid && $type) {
		$iid = getDbFieldValue('ucenter_member', array('id' => $uid), 'iid');
		if ($iid) {
			$list = M('user_coupon uc')
				->join('teach_coupon c ON uc.cid = c.id')
				->join('teach_vice_coupon vc ON vc.coupon_id = c.id')
				->field('uc.id,c.name,c.deduct_price')
				->where(array('uc.iid' => $iid, 'uc.uid' => $uid, 'uc.status' => 0, 'uc.expire_time' => array('gt', time()), 'c.min_price' => array('elt', $price), 'vc.type' => array('IN', '0,' . $type)))
				->select();

			return $list ? $list : array();
		} else {
			return array();
		}
	} else {
		return array();
	}
}

/**
 * 获取 秒杀/团购 课程信息
 * @param        int        $id                 课程ID
 * @param        int        $type               1：面授，2：点播，3：直播
 * @param        int        $price              课程原价
 * @param        int        $is_activity        活动类型；0：无活动，1：拼团，2：秒杀
 * @return       array
 * */
function getActivityCourseInfo($id, $type, $price, $is_activity)
{
	if ($is_activity == 1) {
		if ($type == 1) {
			$db = M('face_course');
		} else if ($type == 2) {
			$db = M('video_course');
		} else {
			$db = M('live_course');
		}
		//拼团
		$info = $db->field('img,name')->where(array('id' => $id, 'is_del' => 0))->find();
		if ($info) {
			$group_info = M('group_work')->field('id,course_id,group_price,chief_price,people_number')->where(array('category' => $type, 'course_id' => $id, 'status' => 1))->order('id desc')->find();
			$group_list = array();
			if ($group_info) {
				$group_list = M('group_join')->field('id,uid')->where(array('gid' => $group_info['id'], 'is_chief' => 1, 'status' => array('IN', '1,2')))->select();
				if ($group_list) {
					foreach ($group_list as &$v) {
						$people_count = M('group_join')->where(array('pid' => $v['id'], 'status' => array('IN', '1,2')))->count();

						//差几人成团
						$surplus_count = $group_info['people_number'] - $people_count - 1;
						$v['surplus_count'] = $surplus_count;

						$v['img'] = getPicture($info['img']);
						$v['name'] = $info['name'];

						$v['real_price'] = $group_info['group_price'];

						if ($v['uid']) $user_info = M('ucenter_member')->field('avatar,username')->where(array('id' => $v['uid']))->find();
						$v['avatar'] = $user_info['avatar'] ? doAvatar($user_info['avatar']) : '';
						$v['username'] = $user_info['username'] ? $user_info['username'] : '';
					}
				}
				$info['price'] = $group_info['group_price'];
			} else {
				$info['price'] = $group_info['chief_price'];
			}

			//拼团数量
			$info['group_len'] = count($group_list);
			//拼团列表
			$info['group_list'] = array_chunk($group_list, 3);
			//正在拼团总人数
			$all_group_people = M('group_join')->where(array('gid' => $group_info['id'], 'status' => 1))->count();
			$info['all_group_people'] = $all_group_people ? $all_group_people : 0;
		} else {
			$info = array();
		}
	} else if ($is_activity == 2) {
		//秒杀
		$info = M('seckill')->field('price')->where(array('course_id' => $id, 'category' => $type))->order('id desc')->find();
	} else {
		$info['price'] = $price;
	}

	return $info;
}

/**
 * 获取课程的价格
 * @param        int        $id                 课程ID
 * @param        int        $type               1：面授，2：点播，3：直播
 * @param        int        $price              课程原价
 * @param        int        $is_activity        活动类型；0：无活动，1：拼团，2：秒杀
 * @param        int        $is_chief           1：团长，2：团员
 * @return       array
 * */
function getCoursePrice($id, $type, $price, $is_activity, $is_chief = 0)
{
	if ($is_activity == 1) {
		$group_info = M('group_work')->field('group_price,chief_price')->where(array('category' => $type, 'course_id' => $id, 'status' => 1))->order('id desc')->find();
		if ($is_chief == 1) {
			$price = $group_info['chief_price'];
		} else if ($is_chief == 2) {
			$price = $group_info['group_price'];
		}
	} else if ($is_activity == 2) {
		$price = M('seckill')->where(array('course_id' => $id, 'category' => $type))->order('id desc')->getField('price');
	}

	return $price;
}

/**
 * 获取课程活动时间
 * @param        int        $id                 课程ID
 * @param        int        $type               1：面授，2：点播，3：直播
 * @param        int        $is_activity        活动类型；0：无活动，1：拼团，2：秒杀
 * @return       array
 * */
function getCourseActivityTime($id, $type, $is_activity)
{
	if ($is_activity == 1) {
		//团购
		$info = M('group_work')->field('start_time,end_time')->where(array('category' => $type, 'course_id' => $id))->order('id desc')->find();
	} else if ($is_activity == 2) {
		//秒杀
		$info = M('seckill')->field('start_time,end_time')->where(array('category' => $type, 'course_id' => $id))->order('id desc')->find();
	}

	return $info;
}

/**
 * 启动秒杀活动
 * @param        int        $seckill_id        秒杀ID；seckill表主键ID
 * @param        int        $category          1：面授，2：点播，3：直播
 * @param        int        $course_id         课程ID
 * @param        int        $status            1：启动，2：停止
 * */
function skillCtr($seckill_id, $category, $course_id, $status)
{
	$db = M();
	$db->startTrans();

	$time = time();

	if ($category == 1) {
		//面授
		$course_data = array(
			'is_activity' => $status == 1 ? 2 : 0,
			'update_time' => $time
		);
		$table = 'teach_face_course';
	} else if ($category == 2) {
		//点播
		$course_data = array(
			'is_activity' => $status == 1 ? 2 : 0,
			'update_time' => $time
		);
		$table = 'teach_video_course';
	} else if ($category == 3) {
		//直播
		$course_data = array(
			'is_activity' => $status == 1 ? 2 : 0,
			'update_time' => $time
		);
		$table = 'teach_live_course';
	}

	$course_res = $db->table($table)->where(array('id' => $course_id))->save($course_data);

	$skill_data = array(
		'status' => $status,
		'update_time' => $time
	);
	$skill_res = $db->table('teach_seckill')->where(array('id' => $seckill_id))->save($skill_data);

	if ($course_res && $skill_res) {
		$db->commit();
	} else {
		$db->rollback();
	}
}

/**
 * 启动/停止 团购活动
 * @param        int        $group_work_id        团购ID；seckill表主键ID
 * @param        int        $category             1：面授，2：点播，3：直播
 * @param        int        $course_id            课程ID
 * @param        int        $status               1：启动，2：停止
 * */
function groupCtr($group_work_id, $category, $course_id, $status)
{
	$db = M();
	$db->startTrans();

	$time = time();

	if ($category == 1) {
		//面授
		$course_data = array(
			'is_activity' => $status == 1 ? 1 : 0,
			'update_time' => $time
		);
		$table = 'teach_face_course';
	} else if ($category == 2) {
		//点播
		$course_data = array(
			'is_activity' => $status == 1 ? 1 : 0,
			'update_time' => $time
		);
		$table = 'teach_video_course';
	} else if ($category == 3) {
		//直播
		$course_data = array(
			'is_activity' => $status == 1 ? 1 : 0,
			'update_time' => $time
		);
		$table = 'teach_live_course';
	}
	$course_res = $db->table($table)->where(array('id' => $course_id))->save($course_data);

	$group_data = array(
		'status' => $status,
		'update_time' => $time
	);
	$group_res = $db->table('teach_group_work')->where(array('id' => $group_work_id))->save($group_data);

	//拼团失败的数据
	$group_join_fail_list = $db->table('teach_group_work')->field('id')->where(array('gid' => $group_work_id, 'is_chief' => 1, 'status' => 1))->select();
	$groupFailRes = true;
	if ($group_join_fail_list) {
		foreach ($group_join_fail_list as &$v) {
			$groupFailRes = groupFail($v['id']);
			if (!$groupFailRes) {
				$groupFailRes = false;
				break;
			}
		}
	}

	if ($course_res && $group_res && $groupFailRes) {
		$db->commit();
	} else {
		$db->rollback();
	}
}

/**
 * 拼团失败处理
 * 1：该团的状态修改为失败
 * 2：order表编辑退款订单号信息
 * 3：order表对应拼团订单进行退款
 * @param        int        $group_join_id        发起拼团的团ID
 * */
function groupFail($group_join_id)
{
	$db = M();
	$db->startTrans();

	$time = time();

	if ($group_join_id) {
		$group_join_data = array(
			'status' => 2,
			'update_time' => $time
		);
		$group_map['id'] = $group_join_id;
		$group_map['pid'] = $group_join_id;
		$group_map['_logic'] = 'OR';
		$group_list = $db->table('teach_group_join')->field('id')->where($group_map)->select();

		if ($group_list) {
			$group_res = true;
			$order_res = true;
			foreach ($group_list as &$v) {
				$order_info = M('order')->where(array('group_join_id' => $v['id']))->find();
				if ($order_info) {
					//该团的状态修改为失败
					$group_res = $db->table('teach_group_join')->where($group_map)->save($group_join_data);
					if (!$group_res) break;

					//order表编辑退款订单号信息
					$back_order_sn = 'BACK' . date('Ymd') . rand(1000, 9999) . $order_info['id'];
					$order_data = array(
						'back_order_sn' => $back_order_sn,
						'update_time' => time()
					);
					$order_res = $db->table('teach_order')->where(array('id' => $order_info['id']))->save($order_data);
					if (!$order_res) break;

					//order表对应拼团订单进行退款
					$data = array(
						'order_sn' => $order_info['pay_order_sn'],
						'out_refund_no' => $back_order_sn,
						'amount' => floatval(0.01) * 100,
//						'amount' => floatval($order_info['pay_price']) * 100,
						'subject' => '拼团失败退款',
						'body' => '拼团失败退款',
						'description' => '拼团失败退款',
						'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/goodsRefundNotice'
					);
					$appid = C('XCX_APPID');
					$user_info = getUserInfo($order_info['uid'], 'openid');
					$openid = $user_info['openid'];
					$obj = new \pay($data, $appid, $openid);
					$obj->applyRefund();
				} else {
					$group_res = false;
					$order_res = false;
					break;
				}
			}

			if ($group_res && $order_res) {
				$db->commit();

				return true;
			} else {
				$db->rollback();

				return false;
			}
		} else {
			$db->rollback();

			return false;
		}
	}
}

/**
 * 机构，供应商 调用 影印资料上传接口
 * */
function uploadCardInfo($sub_mch_code, $user_info, $card_info = array(), $hold_card_info = array())
{
	//上传身份证正反面
	$card_data = array(
		'merchant_type' => 2,
		'user_info' => json_encode($user_info),
		'copy_type' => 1,
		'cert_info' => json_encode($card_info),
		'person_with_id_photo' => json_encode($hold_card_info),
		'sub_mch_code' => $sub_mch_code,
		'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/waitNotice'
	);
	$card_obj = new \pay($card_data);
	$card_obj->upload();

	//上传手持身份证
	$hold_card_data = array(
		'merchant_type' => 2,
		'user_info' => json_encode($user_info),
		'copy_type' => 4,
		'sub_mch_code' => $sub_mch_code,
		'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/infoNotice'
	);
	$hold_card_data['cert_info'] = json_encode(array_merge($card_info, $hold_card_info));

	$hold_card_obj = new \pay($hold_card_data);
	$hold_card_obj->upload();
}

/**
 * 微信支付分账数据入库，返回分账人数据
 * @param        int        $order_id        订单id
 * @return       string
 * */
function getRecceivers($order_id)
{
	$order_info = M('order')->where(array('id' => $order_id))->find();

	$iid = $order_info['iid'];
	$supplier_id = $order_info['supplier_id'];
	$user_info = M('ucenter_member')->field('iid,share_uid')->where(array('id' => $order_info['uid']))->find();

	if ($iid) $institution_info = M('institution')->where(array('id' => $iid))->find();
	if ($supplier_id) $supplier_sub_mch_code = M('supplier')->where(array('id' => $supplier_id))->getField('sub_mch_code');

	$pay_price = $order_info['pay_price'];

	//第三方机构抽佣后剩余的利润
	if ($pay_price >= 0.02) {
		//第三方机构分成金额
		$api_price = sprintf('%.2f', $pay_price * C('API_RATE'));

		$profit_price = $pay_price - $api_price;
	} else {
		$api_price = 0;

		$profit_price = $pay_price;
	}

	/*******************************/

	if ($order_info['type'] == 1) {
		/**
		 * 直播课订单
		 *
		 * tips：机构定价（受到平台成本影响：程序控制最低成本，平台只收取流量费）
		 *
		 * 1：第三方平台抽佣
		 * 2：上级用户收益 = 价格 - 平台流量费用 - 第三方平台抽佣  情况下抽佣
		 * 3：机构收益，剩下的就是机构的收益【需要调用接口进行分账】
		 * */
	} else if ($order_info['type'] == 2) {
		/**
		 * 面授课订单
		 *
		 * tips：机构定价，平台不赚钱
		 *
		 * 1：第三方平台抽佣
		 * 2：如果有上级用户，则上级用户获取收益（利润按比例抽成）
		 * 3：剩下的都是机构【需要调用接口进行分账】
		 * */
		if ($user_info['share_uid'] > 0 && C('SHARE_RATE') > 0 && C('SHARE_RATE') < 100) {
			$share_price = $profit_price * C('SHARE_RATE') / 100;
		} else {
			$share_price = 0;
		}

		//$iid_price = $profit_price - $share_price;
		$iid_price = 0.02;
		if ($iid_price >= C('MIN_SHARE_PRICE')) {
			$institution_recceiver = array();
			if ($institution_info['sub_mch_code']) {
				$institution_recceiver = array(
					'type' => 1,
					'account' => $institution_info['sub_mch_code'],
					'amount' => intval(floatval($iid_price) * 100),
					'description' => '面授课销售机构分账',
				);
			}
		} else {
			$iid_price = 0;
		}
	} else if ($order_info['type'] == 3) {
		/**
		 * 点播课订单
		 *
		 * tips：平台定价，机构抽佣
		 *
		 * 1：第三方平台抽佣
		 * 2：机构抽佣（需要调用接口进行分账）
		 * 3：如果有上级用户，则上级用户获取收益
		 * */

		//机构分账金额
		$iid_price = $profit_price * $institution_info['profit_rate'] / 100;
//		$iid_price = 0.02;
		if ($iid_price >= C('MIN_SHARE_PRICE')) {
			if ($institution_info['sub_mch_code'] && $iid_price) {
				$institution_recceiver = array(
					'type' => 1,
					'account' => $institution_info['sub_mch_code'],
					'amount' => intval(floatval($iid_price) * 100),
					'description' => '在线课销售机构分账',
				);
			}
		} else {
			$iid_price = 0;
		}

		if ($user_info['share_uid'] > 0 && C('SHARE_RATE') > 0 && C('SHARE_RATE') < 100) {
			$share_price = ($profit_price - $iid_price) * C('SHARE_RATE') / 100;
		} else {
			$share_price = 0;
		}
	} else {
		//商城订单
		/**
		 * 点播课订单
		 *
		 * tips：平台定价，机构端抽佣；供应商端进行商品定价的时候，在填写规格时，只需要填写一个成本价，默认销售价与成本价保持一致，当总后台进行商品推荐的时候，需要修改销售价
		 *
		 * 1：第三方平台抽佣
		 * 2：供应商拿成本价，需要调用接口进行分账
		 * 3：机构抽佣，需要调用接口进行分账（下单的时候会携带从哪个机构下单的）
		 * 4：如果有上级用户，则上级用户获取收益（利润按比例抽成）
		 * */
		$spec_list = M('vice_order')->field('old_price,count')->where(array('order_id' => $order_id))->select();

		//书籍成本价（供应商分账金额）
		$supplier_price = 0;
		if ($spec_list) {
			foreach ($spec_list as &$v) {
				$supplier_price += $v['old_price'] * $v['count'];
			}
		}
		$supplier_recceiver = array();
		if ($supplier_sub_mch_code && $supplier_price) {
			$supplier_recceiver = array(
				'type' => 1,
				'account' => $supplier_sub_mch_code,
//			'amount' => intval(floatval($supplier_price) * 100),
				'amount' => intval(floatval(0.02) * 100),
				'description' => '书籍销售供应商分账'
			);
		}

		//第三方机构抽佣，供应商成本分账后剩余的利润
		$surplus_profit_price = $profit_price - $supplier_price;
		//机构分账金额
//		$iid_price = $surplus_profit_price * $institution_info['profit_rate'] / 100;
		$iid_price = 0.02;
		if ($iid_price >= C('MIN_SHARE_PRICE')) {
			$institution_recceiver = array();
			if ($institution_info['sub_mch_code'] && $iid_price) {
				$institution_recceiver = array(
					'type' => 1,
					'account' => $institution_info['sub_mch_code'],
					'amount' => intval(floatval($iid_price) * 100),
					'description' => '面授课销售机构分账',
				);
			}
		} else {
			$iid_price = 0;
		}
	}

	$supplier_price = $supplier_price ? $supplier_price : 0;
	$share_price = $share_price ? $share_price : 0;

	$admin_share_price = $profit_price - $iid_price - $supplier_price - $share_price;

	$order_share_price_data = array(
		'order_id' => $order_id,
		'api_price' => floatval(floor($api_price * 100) / 100),
		'institution_id' => $order_info['iid'],
		'institution_share_price' => floatval(floor($iid_price * 100) / 100),
		'supplier_id' => $order_info['supplier_id'] ? $order_info['supplier_id'] : 0,
		'supplier_share_price' => floatval(floor($supplier_price * 100) / 100),
		'user_id' => $user_info['share_uid'] ? $user_info['share_uidfloatval(floor($str * 100) / 100)'] : 0,
		'user_share_price' => sprintf('%.2f', $share_price),
		'admin_share_price' => floatval(floor(($admin_share_price ? $admin_share_price : 0) * 100) / 100),
		'status' => 0,
		'share_time' => time() + 15 * 24 * 3600,
		'create_time' => time()
	);

	$res = M('order_share_price')->add($order_share_price_data);
	if ($res) {
		$receivers = array();
		if ($institution_recceiver) {
			$receivers[0] = $institution_recceiver;
			if ($supplier_recceiver) $receivers[1] = $supplier_recceiver;
		} else {
			if ($supplier_recceiver) $receivers[0] = $supplier_recceiver;
		}

		return $receivers ? json_encode($receivers) : '';
	} else {
		api_return(2, '支付失败');
	}
}

/**
 * 获取图片的Base64编码(不支持url)
 * @param        file        $img_file        传入本地图片地址
 * @return       string
 */
function imgToBase64($img_file)
{
	$img_base64 = '';

	if (file_exists($img_file)) {
		$app_img_file = $img_file; // 图片路径
//		$img_info = getimagesize($app_img_file); // 取得图片的大小，类型等
		$fp = fopen($app_img_file, "r"); // 图片是否可读权限
		if ($fp) {
			$filesize = filesize($app_img_file);
			$content = fread($fp, $filesize);
			$file_content = chunk_split(base64_encode($content)); // base64编码
			$img_type = "jpg";

			$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
		}

		fclose($fp);
	}

	return $img_base64; //返回图片的base64

}

/**
 * 上级用户分佣
 * @param        int          $uid              支付用户id
 * @param        int          $share_uid        上级用户id
 * @param        float        $price            分账金额
 * */
function incShareUserProfit($uid, $share_uid, $price)
{
	//分佣
	if ($share_uid > 0 && C('SHARE_RATE') > 0 && C('SHARE_RATE') < 100) {
		$username = getDbFieldValue('ucenter_member', array('id' => $uid), 'username');

		$profit = sprintf('%.2f', $price * C('SHARE_RATE') / 100);
		$profit_data = array(
			'uid' => $share_uid,
			'son_uid' => $uid,
			'profit' => $profit,
			'style' => 1,
			'type' => 4,
			'desc' => $username . ' 购买了商品',
			'pay_price' => $price,
			'rate' => C('SHARE_RATE'),
			'create_time' => time()
		);
		M('user_profit')->add($profit_data);

		$user_info = M('ucenter_member')->field('profit,all_profit')->where(array('id' => $share_uid))->find();
		$user_data = array(
			'profit' => $user_info['profit'] + $profit,
			'all_profit' => $user_info['all_profit'] + $profit
		);
		M('ucenter_member')->where(array('id' => $share_uid))->save($user_data);
	}
}

/**
 * 分账成功业务逻辑处理
 * @param        int        $order_id        订单ID
 * */
function shareSuccess($order_id)
{
	$order_share_info = M('order_share_price')->where(array('order_id' => $order_id))->find();

	$time = time();
	$share_data = array(
		'status' => 2,
		'update_time' => $time
	);
	$res = M('order_share_price')->where(array('order_id' => $order_id))->save($share_data);
	if ($res && $order_share_info['user_id']) {
		$order_info = M('order')->where(array('id' => $order_id))->find();

		//因为当从购物车购买书籍时，可能书籍来自于多个供应商，order_share_price表会产生多条数据，所以需要求和
		$sum_user_share_price = M('order_share_price')->where(array('order_id' => $order_id))->sum('user_share_price');
		incShareUserProfit($order_info['uid'], $order_share_info['user_id'], $sum_user_share_price);
	}
}

/**
 * file_get_contents 发起post请求
 * @param        string        $api          接口名
 * @param        array         $param        请求参数
 * @param        array
 * */
function sendApi($api, $param = array())
{
	if ($param) {
		$param = http_build_query($param);  //把参数转换成URL数据

		$context = array(
			'http' => array(
				'method' => 'POST',
				'header' => 'Content-type: application/x-www-form-urlencoded',
				'content' => $param
			)
		);

		$context = stream_context_create($context);
	} else {
		$context = null;
	}
	$url = getHost() . '/index.php/Home/' . $api;
	$data = file_get_contents($url, false, $context);

	return $data;
}

function http_request($url, $fields = [], $second = 30)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_TIMEOUT, $second);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	if (isset($fields)) {
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	}
	$data = curl_exec($ch);
	if (!$data) {
		$error = curl_errno($ch);
		$data = '<xml><err_code>' . $error . '</err_code><err_code_des>curl' . $error . '</err_code_des></xml>';
	}
	curl_close($ch);

	return $data;
}

function AccessToken()
{
	$appid = C('XCX_APPID');
	$secret = C('XCX_APPSECRET');
	$tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
	$tokenArr = json_decode(http_request($tokenUrl));

	return $tokenArr->access_token;
}

/**
 * 生成机构二维码
 * @param        int        $id         任务位置id；关联plan_position表主键id
 * @param        int        $uid        用户id
 * @return       string
 * */
function createInstituteQr($iid)
{
	$redirect_url = 'pages/login/login?iid=' . $iid;
	$access_token = AccessToken();

	$path = $redirect_url;
	$width = 200;//生成小程序码尺寸
	$post_data = '{"path":"' . $path . '","width":' . $width . '}';
	$url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;//小程序码
	$result = http_request($url, $post_data);

	$save_qr_qath = './Uploads/Picture/instituteQr/';
	if (!is_dir($save_qr_qath)) mkdir($save_qr_qath, 0777, true);

	$rand = rand(10000000, 99999999);
	$res = file_put_contents($save_qr_qath . $rand . '.jpg', $result);
	if ($res) {
		return str_replace('.', '', $save_qr_qath) . $rand . '.jpg';
	} else {
		api_return(2, '系统繁忙，请稍后再试');
	}
}

/**
 * 发起application/json请求
 * */
function json_post($url, $data = null)
{
	$curl = curl_init();

	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	if (!$data) {
		return 'data is null';
	}
	if (is_array($data)) {
		$data = json_encode($data);
	}
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	curl_setopt($curl, CURLOPT_HEADER, 0);
	curl_setopt(
		$curl, CURLOPT_HTTPHEADER, array(
			     'Content-Type: application/json; charset=utf-8',
			     'Content-Length:' . strlen($data),
			     'Cache-Control: no-cache',
			     'Pragma: no-cache'
		     )
	);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$res = curl_exec($curl);
	$errorno = curl_errno($curl);
	if ($errorno) {
		return $errorno;
	}
	curl_close($curl);

	return $res;
}

/**
 * 获取域名前缀
 * */
function get_host()
{
	$res = is_ssl();
	if ($res) {
		return 'https://' . $_SERVER['HTTP_HOST'];
	} else {
		return 'http://' . $_SERVER['HTTP_HOST'];
	}
}

/**
 * 根据id获取多张图片路径
 * */
function get_imgs($ids)
{
	$map['id'] = array('IN', $ids);
	$img_list = M('picture')->field('id,path as img')->where($map)->select();
	foreach ($img_list as $k => $v) {
		$img_list[$k]['img'] = get_host() . $v['img'];
	}

	return $img_list ? $img_list : [];
}

/**
 * 根据id获取多张图片路径
 * */
function get_img($id)
{
	$path = M('picture')->field('id,path as img')->where(['id' => $id])->getField('path');

	return $path ? get_host() . $path : '';
}